#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
|===== Conference Bot Plugin ============
|= User Commands
|===== By: ==============================
|= Patrick Kennedy
|===== Current Version: =================
|= 1.0
|===== Description: =========================================
|= Commands any user can use.
|===== Additional Comments: =================================
|= 
|============================================================"""

from utils import *
from random import randrange

def init(bot):
	bot.addCommand("away", cmd_away)
	bot.addHook("message", hook_away)
	bot.addCommand("dice", cmd_dice)
	bot.addCommand("me", cmd_me)
	bot.addCommand("msg", cmd_msg)
	bot.addMuteCommand("away", cmd_away)

def unload(bot):
	bot.removeCommand(['away', 'me', 'msg'])
	bot.removeHook('hook_away')

def cmd_away(bot, user, msg):
	"""Set yourself as away.
Usage: )away [message]
Type )away to toggle your status.
While away you will not recive any messages and sending a message will make you unaway."""
	
	msg = msg.strip().lower()
	if msg in ['s','silent']:
		add_userflag(user, "options", 'silent')
	if msg or not isaway(getjid(user)):
		sub_nochat(bot, user, msg)
	else:
		sub_chat(bot, user, msg)

def sub_nochat(bot, user, reason):
	addaway(user.getStripped().lower())
	if reason:
		reason = "(Reason: %s)" % reason
	if not has_userflag(user, "options", 'silent'):
		bot.systoall('%s is temporarily away. %s' % (getdisplayname(user), reason), [user])
	bot.sys(user, "Warning: You have marked yourself as away. You will not recive any messages untill you use ')away' or send a message.") 
	
def sub_chat(bot, user, msg):
	if not del_userflag(user, "options", 'silent'):
		bot.systoall('%s is actively interested in chatting.' % (getdisplayname(user)), [user])
	delaway(user)
	bot.sys(user, 'You can begin to chat now.')

def hook_away(bot, args):
	user = getjid(args[0])
	if del_userflag(user,"status","away"):
		bot.sys(user,"Because you said something you have been marked unaway.")
	return False
	
def cmd_dice(bot, user, args):
	"""Rolls a random number.
Usage: )dice [[<number of dice>][d<number of sides>]]
Example: /dice 2d10"""
	dice = 1
	sides = 6
	total = []
	
	if args:
		if 'd' in args:
			dice, sides = args.split('d', 2)
			if ' ' in sides:
				sides = sides[:sides.find(' ')]
		else:
			dice = args
		
		if dice.isdigit() and sides.isdigit():
			dice, sides = int(dice), int(sides)
			if dice > 25:
				dice = 25
				bot.error(user, "The number of sides has been set to 25.")
			elif dice < 1:
				dice = 1
				bot.error(user, "The number of dice has been set to 1.")
			
			if sides > 100:
				sides = 100
				bot.error(user, "The number of sides has been set to 100.")
			elif sides < 4:
				sides = 4
				bot.error(user, "The number of sides has been set to 4.")
		else:
			bot.error(user, cmd_dice.__doc__)
			return

	for i in range(dice):
		total.append(randrange(1, sides + 1))
		
	bot.systoall("""%s rolls %s with %s %s-sided %s
	%s""" % (getdisplayname(user),
			reduce((lambda x, y: x + y), total), 
			(lambda x: x == 1 and "a" or x)(dice),
			sides,
			(lambda x: x == 1 and "die" or "dice")(dice),
			reduce((lambda x, y: str(x) + " | " + str(y)), total)))
									
def cmd_me(bot, user, msg):
	"""Send an action to the world.
Usage: )me <action>"""
	msg = msg.decode('utf-8')
	if not msg:
		bot.error(user, cmd_me.__doc__)
	bot.sendtoall("**%s %s**" % (getdisplayname(user), msg), log = True)	
		
def cmd_msg(bot, user, msg):
	"""Send a user a private message.
Usage: )msg <displayname> <message>"""
	if not ' ' in msg:
		bot.msg(user, cmd_msg.__doc__)
	else:
		if has_userflag(user, "status", 'away'):
			bot.sys(user, 'Warning: Because you set "away" flag, so you can not receive and send any message from this bot, until you reset using ")away" command') 
			return
		target,msg = msg.split(' ',1)
		target = getjid(target.lower())
		if has_userflag(target,"status", 'away') and not isadmin(user):
			bot.sys(who, "<%s> has set himself 'away', so you can't message them." % getdisplayname(target)) 
			return
		#if isbusy(target):
		#	bot.sys(who, '<%s> has is busy or is idle so the message has not been delivered.' % getdisplayname(target))
		#	return
		if not isuser(bot, target):
			bot.msg(user, "The user _%s_ doesn't seem to exist." % target)
			return
		elif not isonline(bot, target):
			bot.msg(user, "%s is offline and cannot receive messages." % getdisplayname(target).capitalize())
			return
		
		bot.log("<"+getdisplayname(user)+">" + " to <"+getdisplayname(target)+">", msg)
		bot.msg(target, '*<%s<* %s' % (getdisplayname(user), msg))
		bot.msg(user, '>%s> %s' % (getdisplayname(target), msg))
